import React, { useEffect, useRef, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import { Upload, Form } from 'antd';
import { upFileToOSS } from '@/ui/xx-AliyunOSSUpload/client/AliOss';
import OSS from 'ali-oss';

// 客户端直接上传文件到OSS
const client = new OSS({
    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: "oss-cn-shenzhen",
    // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    accessKeyId: "LTAI5tLjcwZQRWbd7duLotwo",
    accessKeySecret: "GcRJyGSJbbmmxnDfY1c168mJmbfsSE",
    // 填写Bucket名称。
    bucket: "bigkel-com",
});

/**@description 用于Form表单中上传图片 */
const XxFormItemUpload = ({
    uploadProps = {
        maxCount: 1
    },

}) => {
    const [fileList, setFileList] = useState([]);

    const props = {
        maxCount: 5,
        accept: 'image/png,image/jpg,image/jpeg',
        name: "file",
        action: "",
        beforeUpload(file) {
            /**
             * 上传之前可以检测图片是否符合要求，如果不符合，可以调用this.onRemove(file)移除图片，并需要return false;
             */
        },
        onRemove(file) {
            let list = fileList.filter(item => item.name !== file.name)
            setFileList(list);
        },
        onChange({ file, fileList }) {
            let newFileList = [];
            console.log("onChange图片列表：", fileList);
            if (fileList.length > 0) {

                newFileList = fileList.map(item => {
                    if (item.status === "done") {
                        console.log("上传成功的回调：", item)
                        return {
                            name: item.response.name,
                            url: item.response.url,
                            size: item.size,
                            uid: item.uid
                        }
                    }
                })
            }
            console.log("onChange组装后图片列表：", newFileList);
            setFileList(newFileList);
        },
        customRequest: async ({ file, onSuccess, onError }) => {
            let metaData = {
                fileName: file.name,
                busiId: `contractEntity.contractCode`,
                busiType: 'OBC'
            }
            let res = await upFileToOSS(file, metaData);
            onSuccess(res)
        },
        multiple: true,
        ...uploadProps

    }

    const initImage = async (fileName) => {
        let metaData = {
            fileName: fileName,
            busiId: `contractEntity.contractCode`,
            busiType: 'OBC'
        }
        let res = await downloadFileFromOSS(metaData);
        if (res.status === "0000") {
            setFileList([{
                url: res?.data?.url,
                uid: uuid(),
                size: res?.data?.size
            }])
        } else {
            message.error("图片加载失败")
        }
    }


    return (


        <Upload
            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
            listType="picture-card"
            showUploadList={{ showPreviewIcon: false }}

            {...props}
        >
            {
                fileList.length >= props.maxCount ? null : <div>
                    <PlusOutlined />
                    <div
                        style={{
                            marginTop: 8,
                        }}
                    >
                        上传
                    </div>
                </div>
            }
        </Upload>

    )
}

export default XxFormItemUpload;